
package com.zntg.api.shuanglu;
import com.zntg.api.renGouShu.bo.TblobstorageBo;
import com.zntg.api.renGouShu.enmus.ResultStatus;
import com.zntg.api.renGouShu.entity.TblobstorageEntity;
import com.zntg.api.renGouShu.result.ResultModel;
import com.zntg.api.shuanglu.enums.ShuangLuResultStatus;
import com.zntg.api.shuanglu.param.DoubleViedoGetParam;
import com.zntg.api.shuanglu.param.DoubleViedoUpdateParam;
import com.zntg.api.shuanglu.result.DoubleViedoResult;
import com.zntg.api.shuanglu.result.DownloadFileResult;
import com.zntg.contants.ShuangLuApiContants;
import com.zntg.entity.TblobstorageNewEntity;
import com.zntg.mapper.aiiidb.DoubleViedoAcceDtlMapper;
import com.zntg.mapper.crmdb.DoubleViedoAcceCrmMapper;
import com.zntg.mapper.crmdb.TblobStorageDoubleViedoMapper;
import com.zntg.mapper.crmdb.TblobtSorageMapper;
import com.zntg.utils.DateUtil;
import com.zntg.utils.DownloadPdf;
import com.zntg.utils.FileUtils;
import com.zntg.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
 * @Description: 双录视频同步到crm
 * @Author: zhengyunfei
 * @Date: 2018/6/15
 * @time:11:26
 */
@SuppressWarnings("ALL")
@Api(value = ShuangLuApiContants.NAMESPACE,tags =  ShuangLuApiContants.NAMESPACE )
@RestController
@RequestMapping("/api/v2/shuanglu")
public class ShuangLuApiController {
    @Value("${template.targetPath}")
    String targetPath;
    @Autowired
    private Environment env;
    @Autowired
    private DoubleViedoAcceDtlMapper doubleViedoAcceDtlMapper;
    @Autowired
    private DoubleViedoAcceCrmMapper doubleViedoAcceCrmMapper;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    @Autowired
    private TblobStorageDoubleViedoMapper tblobStorageDoubleViedoMapper;
    @PostMapping(value = "/syncToCrm",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "双录视频CRM同步逻辑",notes = "处理双录视频到CRM同步逻辑",position = 1,response = Object.class)
    @ResponseBody
    public Object crmSync(DoubleViedoGetParam param){
        System.out.println("录完合同后，处理crm同步逻辑,reserveId===="+param.getReserveId()+",htNo===="+param.getHtNo()+",userId===="+param.getUserId());
        ResultModel resultModel=new ResultModel();
        Map<String,Object> resultMap=new HashMap<>();
        Map<String,Object> queryMap=new HashMap<>();
        try{
            String reserveId=param.getReserveId();//预约编号
            //参数校验
            if (validParam(resultModel, param)) return resultModel;
            //第一步：获取需要同步的文件
            queryMap.put("reserveId",reserveId);
            DoubleViedoResult doubleViedoResult=doubleViedoAcceDtlMapper.findById(queryMap);
            System.out.println("获取到的需要同步的文件==============="+doubleViedoResult);
            if(!StringUtil.isNullOrEmpty(doubleViedoResult)){
                String doubleViedoUrl=doubleViedoResult.getDoubleViedoUrl();
                //获取crmAcceId
                String crmAcceId=tblobtSorageMapper.getTblobStorageSeq()+"";
                //根据预约编号获取cSubkeyId
                String cSubkeyId=doubleViedoAcceCrmMapper.getCSubkeyId(queryMap);
                Map<String,Object> userIdMap=new HashMap<>();
                userIdMap.put("userId",param.getUserId());
                String cNodeCode=doubleViedoAcceCrmMapper.getDept(userIdMap);
                //下载远程双录文件到本地
                String fileSize="";
                String today= DateUtil.getToDay();
                String fileSaveName=crmAcceId+"baccessory";
                String filePath=targetPath+today+"/Tblobstorage/"+crmAcceId.substring(0,crmAcceId.length()-1)+"/";
                File file=new File(filePath+fileSaveName);
                    if(file.exists()){
                        file.delete();
                    }
                   FileUtils.createFile(filePath+fileSaveName);
                   DownloadFileResult downloadFileResult= DownloadPdf.downLoadByUrl(doubleViedoUrl,
                           fileSaveName,filePath);
                    fileSize=downloadFileResult.getFileSize();
                    //插入crm附件表
                    TblobstorageNewEntity tblobstorageBo=new TblobstorageNewEntity();
                    tblobstorageBo.setlStorageid(crmAcceId);
                    tblobstorageBo.setcSubkeyid(cSubkeyId);
                    String fileName=param.getHtNo()+"双录"+".mp4";
                    tblobstorageBo.setcFilename(fileName);
                    tblobstorageBo.setlFilesize(fileSize);
                    tblobstorageBo.setcCreator(param.getUserId());
                    tblobstorageBo.setcNodecode(cNodeCode);
                    tblobStorageDoubleViedoMapper.add(tblobstorageBo);
                System.out.println("tblobStorageDoubleViedoMapper==========插入附件表成功");
                    //第三步：更新双录视频对应的字段CRM_ACCE_ID
                    DoubleViedoUpdateParam doubleViedoUpdateParam=new DoubleViedoUpdateParam();
                    doubleViedoUpdateParam.setCrmAcceId(crmAcceId);
                    doubleViedoUpdateParam.setResreveId(doubleViedoResult.getReserveId());
                    doubleViedoAcceDtlMapper.update(doubleViedoUpdateParam);
                System.out.println("更新双录对应的crmacceId==============================成功");


            }
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
            resultModel.setData(null);
        }
        return resultModel;
    }
    /**
    * @Description: 参数校验
    * @Author: zhengyunfei
    * @Date: 2019/6/24
    * @time:13:43
    */
    private boolean validParam(ResultModel resultModel, DoubleViedoGetParam param) {
        String reserveId=param.getReserveId();//预约编号
        if(StringUtil.isNullOrEmpty(reserveId)){
            resultModel.setCode(ShuangLuResultStatus.RESERVE_ID_NOTNULL.getCode());
            resultModel.setMessage(ShuangLuResultStatus.RESERVE_ID_NOTNULL.getMessage());
            return true;
        }
        String htNo=param.getHtNo();//合同号
        if(StringUtil.isNullOrEmpty(htNo)){
            resultModel.setCode(ShuangLuResultStatus.HT_NO_NOTNULL.getCode());
            resultModel.setMessage(ShuangLuResultStatus.HT_NO_NOTNULL.getMessage());
            return true;
        }
        String userId=param.getUserId();//员工编号
        if(StringUtil.isNullOrEmpty(userId)){
            resultModel.setCode(ShuangLuResultStatus.USER_NO_NOTNULL.getCode());
            resultModel.setMessage(ShuangLuResultStatus.USER_NO_NOTNULL.getMessage());
            return true;
        }
        return false;
    }



}
